package androcr.client.mobile.services.texttospeech;

import java.util.Locale;

import androcr.client.mobile.core.Controller;
import androcr.client.mobile.display.texttospeech.ITextToSpeechActivity;
import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;

public class TextToSpeechPresenter implements ITextToSpeechPresenter, OnInitListener {
	private static final String TAG = "CameraPresenter";
	
	private ITextToSpeechActivity ttsActivity;
	private TextToSpeech tts;
	
	public TextToSpeechPresenter(ITextToSpeechActivity textToSpeechActivity) {
		ttsActivity = textToSpeechActivity;
		
		// Initialize text-to-speech. This is an asynchronous operation.
        // The OnInitListener (second argument) is called after initialization completes.
        tts = new TextToSpeech((Context) ttsActivity, this);
	}

	@Override
	public void onInit(int status) {
		// status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.
        if (status == TextToSpeech.SUCCESS) {
            // Set preferred language to US english.
            int result = tts.setLanguage(Locale.US);
            if (result == TextToSpeech.LANG_MISSING_DATA ||
                result == TextToSpeech.LANG_NOT_SUPPORTED) {
               // Language data is missing or the language is not supported.
                Log.e(TAG, "Language is not available.");
            } else {
                // The TTS engine has been successfully initialized.
                // Allow the user to press the button for the app to speak.
            	ttsActivity.setIsTtsReady(true);
                // Greet the user.
            }
        } else {
            // Initialization failed.
            Log.e(TAG, "Could not initialize TextToSpeech.");
        }
	}

	@Override
	public void readText() {
		String text = ttsActivity.getDisplayedTextToRead().toString();
        tts.speak(text,
            TextToSpeech.QUEUE_FLUSH,  // Drop all pending entries in the playback queue.
            null);
	}

	@Override
	public CharSequence getTextToRead() {
		return Controller.getInstance().getActualRecognizedText();
	}

	@Override
	public void stopTextToSpeech() {
        if (tts != null) {
            tts.stop();
        }
	}

	@Override
	public void shutdownTextToSpeech() {
		if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
	}
}
